package ltd.smallwang.springdemos.filter;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author smallwang
 * @email justdoalitter@gmail.com
 * @create date 2024-09-15 11:37:06
 * @modify date 2024-09-15 11:37:06
 * @desc 请求报文可重复读
 */
@Component
@Slf4j
public class CacheReqBodyFilter implements Filter {

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain)
      throws IOException, ServletException {
    if (servletRequest instanceof HttpServletRequest httpServletRequest) {
      MultiReadHttpServletRequest multiReadHttpServletRequest = new MultiReadHttpServletRequest(
          httpServletRequest);
      try (InputStream inputStream = multiReadHttpServletRequest.getInputStream();) {
        String body = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        System.out.println(body);
        log.info("req body size is {}", body.length());
      }
      filterChain.doFilter(multiReadHttpServletRequest, servletResponse);
    } else {
      filterChain.doFilter(servletRequest, servletResponse);
    }
  }

}
